package ;
import hxjson2.JSON;
import js.Dom;
import js.JQuery;
import js.Lib;
import me.cunity.debug.Out;

/**
 * ...
 * @author Axel Huizinga axel@cunity.me
 */

class Xml2Json 
{
	static function _(sel:String):JQuery { return new JQuery(sel); }
	
	static var tmpObj:Dynamic;
	
	public static function create(xdata:String):Dynamic
	{
		tmpObj = {};
		var xml:JQuery = _(xdata);
		//var children = xml.find('menu').get();
		var children = xml.get();
		trace(children.length);
		//trace(untyped xml.find('menu').prevObject[2]);
		
		//Out.dumpObject(untyped xml.find('menu'));
		//trace(xml.find('menu').parents());
		//xml.find('menu').each(function():Void { trace(JQuery.cur.get()[0].nodeName + ':' ); } );
		//trace(xml.find('#menu').andSelf().get().length);
		//trace(xml.find('#menu').andSelf().get()[2] + ':' + Reflect.fields(xml.find('#menu').andSelf().get()[2] ).join("<br/>"));
		//trace(xml.find('menu').parent().nodeName);
		//trace(xml.find('menu').children().length);
		//trace(xml.find('menu').get()[0].nodeName);
		for (child in children)
			scan(child);
			//trace(child.nodeName);
		//xml.each(function():Void { trace(JQuery.cur.get()[0].nodeName + ':' + untyped __js__("$(this).get(0).nodeName")); } );
		//xml.each(function():Void { trace(JQuery.cur.attr('id') + ':' + JQuery.cur.index()); } );
		//trace(Std.string(tmpObj));
		
		trace(JSON.encode(tmpObj));
		//return JSON.decode( tmpObj );
		return JSON.decode( JSON.encode(tmpObj) );
	}
	
	public static function scan(node:HtmlDom)
	{
		//if(node.nodeType == 1)
			//trace(node.nodeName + ':' + node.id);
		if (node.nodeName == 'DIV')
		{
			var menuContainer:Dynamic = { };
			if (node.getAttribute('orient') != null)
				menuContainer.orient = node.getAttribute('orient');
			if (node.getAttribute('align') != null)
				menuContainer.align = node.getAttribute('align');
			menuContainer.className = node.className;
			menuContainer.items = new Array<Dynamic>();
			for (c in 0...node.childNodes.length)
			{
				if (node.childNodes[c].nodeName == 'A')
				{
					var item:Dynamic = { id:node.childNodes[c].id };
					if (node.childNodes[c].getAttribute('href') != null)
						item.href = node.childNodes[c].getAttribute('href');					
					if (node.childNodes[c].getAttribute('target') != null)
						item.target = node.childNodes[c].getAttribute('target');
					if (node.childNodes[c].getAttribute('pack') != null)
						item.pack = node.childNodes[c].getAttribute('pack');
					item.text = node.childNodes[c].innerHTML;
					menuContainer.items.push(item);
				}
				//traverse(node.childNodes[c]);
			}
			Reflect.setField(tmpObj, node.id, menuContainer);
			//tmpObj.menu.push(menuContainer);
		}

	}
}